﻿using System.Diagnostics.CodeAnalysis;
using System.Threading;
using OrderMicroService.Infrastructure.Repository.DAO;
using OrderMicroService.Infrastructure.Repository.Common;
using OrderMicroService.Types.Types;

namespace OrderMicroService.Infrastructure.Repository.Impl
{
    public class ThreadLocalAggregateManager<T, ID> : IAggregateManager<T, ID>
        where T : IAggregate<ID>
        where ID : IIdentifier
    {
        private readonly ThreadLocal<DbContext<T, ID>> context;

        public ThreadLocalAggregateManager()
        {
            context = new ThreadLocal<DbContext<T, ID>>(() => new DbContext<T, ID>());
        }

        public static ThreadLocalAggregateManager<T, ID> NewInstance()
        {
            return new ThreadLocalAggregateManager<T, ID>();
        }

        public void Attach([NotNull] T aggregate)
        {
            context.Value.Attach(aggregate);
        }

        public void Attach([NotNull] T aggregate, [NotNull] ID id)
        {
            context.Value.SetId(aggregate, id);
            context.Value.Attach(aggregate);
        }

        public void Detach([NotNull] T aggregate)
        {
            context.Value.Detach(aggregate);
        }

        public T Find([NotNull] ID id)
        {
            return context.Value.Find(id);
        }

        public void Merge(T aggregate)
        {
            context.Value.Merge(aggregate);
        }

        public EntityDiff DetectChanges(T aggregate)
        {
            throw new System.NotImplementedException();
        }
    }
}